package fdoj.eventInvitations.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;

import fdoj.eventInvitations.dao.EventDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Invantation;
import fdoj.eventInvitations.entity.Person;
import fdoj.eventInvitations.entity.Response;
import fdoj.eventInvitations.util.SendMail;

public class CancelEventController extends HttpServlet{
	@EJB
	private EventDao eventDao;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Person loggedUser = (Person) request.getSession().getAttribute("loggedUser");
				if (loggedUser == null) {
					response.sendRedirect(response.encodeRedirectURL("./index"));
					return;
		    }
			String id  = request.getParameter("id");
			Event e = eventDao.findById(Integer.parseInt(id));
			e.setCanceled(true);
			eventDao.merge(e);
			SendMail sm = new SendMail();
			for(Contact c : e.getAttending()){
				String text = "Dogadjaj " + e.getTitle() + " je otkazan.";
				String subject = "Obavestenje o otkazivanju dogadjaja.";
				sm.Send(c.getEmail(), text, subject);
			}
			response.sendRedirect(response.encodeRedirectURL("./home"));
			return;		
		}catch (Exception e) {
			// TODO: handle exception
		}
		response.sendRedirect(response.encodeRedirectURL("./error.jsp"));
	}
}
